package seclog.util;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;

public class Networking {
	
	private static int socketTimeout = 5; // socket connection timeout
	
    /*
     * Opens a socket connection to a host
     * Input: server name, port number
     * Output: socket
     * Author: Mikhail Strizhov	
     */
    public static Socket openSocket(String server, int port) throws Exception
    {
        Socket socket;

        // create a socket with a timeout
        try {
            InetAddress inteAddress = InetAddress.getByName(server);
            SocketAddress socketAddress = new InetSocketAddress(inteAddress, port);

            // create a socket
            socket = new Socket();

            int timeoutInMs = socketTimeout * 1000;
            socket.connect(socketAddress, timeoutInMs);
            
            return socket;
        }
        catch (SocketTimeoutException e)
        {
            System.err.println("Timed out waiting for the socket.");
            e.printStackTrace();
            throw e;
        }
    }
}
